import Vue from 'vue'
import VueRouter from 'vue-router'
import { routes } from './routes'
import store from '@/store'
import moment from 'dayjs'
import jwt from 'jsonwebtoken'

Vue.use(VueRouter)

const router = new VueRouter({
  linkExactActiveClass: 'layui-this',
  routes
})

router.beforeEach((to, from, next) => {
  // 尝试从缓存中读取token 和用户信息
  const token = localStorage.getItem('frontToken')
  const userInfo = localStorage.getItem('frontUserInfo')

  if (token !== null && token !== '') {
    const payLoad = jwt.decode(token)
    if (moment().isBefore(moment(payLoad.exp * 1000))) {
      store.commit('SET_TOKEN', token)
      store.commit('SET_USER_INFO', JSON.parse(userInfo))
      store.commit('SET_ISLOGIN', true)
      if (!store.state.ws) {
        store.commit('INIT_WEBSOCKET', {})
      }
    } else {
      localStorage.clear()
    }
  }

  if (to.matched.some(record => record.meta.requiresAuth)) {
    const isLogin = store.state.isLogin
    if (isLogin) {
      // 已登录就直接正常跳转
      next()
    } else {
      // 没登录就去登录页面
      next('/login')
    }
  } else {
    // 公共页面 不需要登录
    next()
  }
})


export default router
